<?php
/**
 * Created by 张彪.
 * User: 小马出行
 * Date: 2017/10/31
 * Time: 17:44
 */
namespace app\api\logic;

use app\api\model\InvoiceModel;
use app\api\model\PayLogModel;
use app\api\model\UserModel;
use app\api\model\WalletModel;
use my\Security;
use my\Tools;
use think\Model;

class InvoiceLogic extends Model
{
    /**
     * 获取待开发票的订单信息
     * @param $map
     * @param $field
     * @param $page
     * @param $limit
     * @return array
     * */
    public function getInvoiceOrderList($map,$field=array('inner'=>'*','inter'=>'*'),$page=1,$limit=10)
    {
        $invoice = new InvoiceModel();
        $limit_inner = $limit_inter = floor($limit/2);//均分
        $count_inner = $invoice->countOrderInner($map['inner']);//符合条件的城内订单数
        $count_inter = $invoice->countOrderInter($map['inter']);//符合条件的城际订单数
        if($count_inner>$limit_inner&&$count_inter<$limit_inter){
            $limit_inner = $limit-$count_inter;
            $limit_inter = $count_inter;
        }elseif($count_inner<$limit_inner&&$count_inter>$limit_inter){
            $limit_inner = $count_inner;
            $limit_inter = $limit-$count_inner;
        }
        $res_inner = $invoice->getInvoiceOrderInner($map['inner'],$field['inner'],true,$page,$limit_inner);//城内订单
        $res_inter = $invoice->getInvoiceOrderInter($map['inter'],$field['inter'],true,$page,$limit_inter);//城际订单
        if($res_inner === false || $res_inter === false){
            return array('status'=>0,'msg'=>'查询异常');
        }
        if(!empty($res_inner)){
            foreach ($res_inner as $key=>$val){
                $res_inner[$key]['order_model'] = 'inner';
            }
        }
        if(!empty($res_inter)){
            foreach ($res_inter as $k=>$v){
                $res_inter[$k]['order_model'] = 'inter';
                ($v['need_price'])&&$res_inter[$k]['need_price'] = $v['need_price']*100;
            }
        }
        $res['inner'] = $res_inner ? decode_array_2($res_inner):array();
        $res['inter'] = $res_inter ? decode_array_inter_2($res_inter) : array();
        return array('status'=>1,'data'=>array_merge($res['inner'],$res['inter']));
    }

    /**
     *判断订单是否非出租车订单，有无重复重复提交
     * @param $order_common_id
     * @param $uid
     * @return array
     * */
    public function checkOrder($order_common_id,$uid)
    {
        $order_common_inner = db('order_common');
        $order_common_inter = db('order_common',config('intercity_db'));
        //1:inner;2:inter
        $order_common_ids = $order_common_id_ori = explode(';',trim($order_common_id,';'));
        foreach ($order_common_ids as $key => $val){
            $data_ = explode('-',trim($val,'-'));
            if(!in_array($data_[0],array('inner','inter'))){
                return array('status'=>0,'msg'=>'订单参数错误');
                break;
            }
            $data_[0]=='inner'&&$k = 'common_id';
            $data_[0]=='inter'&&$k = 'id';
            $map[$data_[0]][$k][]=$data_[1];
        }
        /*******************判断传来的订单id对应的订单类型是否可以开具发票及有无重复开具发票*******************************/
        $field = "invoice_id";
        $map_inner['is_valid'] = $map_inter['is_valid'] = 1;//有效的发票记录公共参数
        $map_inner['order_common_id'] = $map_inner_['common_id'] = array('in',$map['inner']['common_id']);
        $map_inner['invoice_type'] = 1;//城内
        $map_inter['order_common_id'] = $map_inter_['id'] = array('in',$map['inter']['id']);
        $map_inter['invoice_type'] = 2;//城际
        $inner_invoice = $this->searchInvoice($map_inner,$field);
        $inter_invoice = $this->searchInvoice($map_inter,$field);
        if(!empty($inner_invoice) || !empty($inter_invoice)){
            return array('status'=>0,'msg'=>'请不要重复申请发票');
        }
        $trip = new TripLogic();
        foreach ($map['inner']['common_id'] as $key=>$id){
            $order_type = $trip->getTripById($id,'order_type')['order_type'];
            if($order_type==2){
                return array('status'=>0,'msg'=>'本平台不开具出租车行程发票');
                break;
            }
        }
        /*******************判断传来的id对应的订单状态是否可以开具发票*******************************/
        $map_inner_['uid'] = $map_inter_['member_id'] = $uid;
        $map['inner']['common_id']&&$inner_order_status = $order_common_inner->where($map_inner_)->column('order_status');
        $map['inter']['id']&&$inter_order_status = $order_common_inter->where($map_inter_)->column('order_status');
        if(($map['inner']['common_id']&&empty($inner_order_status)) || ($map['inter']['id']&&empty($inter_order_status))){
            return array('status'=>0,'msg'=>'存在不属于您的订单信息');
        }
        foreach ($inner_order_status as $val){
            if(!in_array($val,array(45,50))){
                return array('status'=>0,'msg'=>'该订单没有结束，无法发票');
                break;
            }
        }
        foreach ($inter_order_status as $value){
            if(!in_array($value,array(45,50))){
                return array('status'=>0,'msg'=>'该订单没有结束，无法发票');
                break;
            }
        }
        /*******************统计发票的价格及订单id*******************************/
        $money_inner = $order_common_inner->where($map_inner_)->sum('need_price');
        $money_inter = $order_common_inter->where($map_inter_)->sum('need_price');
        $money = $money_inner+($money_inter*100);
        return array('status'=>1,'msg'=>'ok','map'=>$map,'money'=>$money);
    }

    /**
     * 根据id获取发票详情
     * @param $id
     * @param $field
     * @param $flag //true为返回解码后的数据
     * @return array
     * */
    public function getInvoiceById($id,$field='*',$flag = true)
    {
        $invoice = new InvoiceModel();
        $res = $invoice->getInvoiceById($id,$field);
        if($res === false){
            return array('status'=>0,'msg'=>'查询异常');
        }
        $res = $flag?decode_array($res):$res;
        return array('status'=>1,'data'=>$res);
    }

    /**
     * 获取已开发票的订单信息
     * @param $map
     * @param $field
     * @param $page
     * @param $limit
     * @return array
     * */
    public function getInvoiceCommonList($map,$field='*',$page=1,$limit=10)
    {
        $invoice = new InvoiceModel();
        $res_common = $invoice->getInvoiceCommonList($map,$field,$page,$limit);
        if($res_common === false){
            return array('status'=>0,'msg'=>'查询异常');
        }
        $res_common = $res_common?decode_array_2($res_common):$res_common;
        if($res_common){
            foreach ($res_common as $index=>$value){
                $map_['b.invoice_common_id'] = $value['invoice_common_id'];
                $field_ = "c.order_time,c.start_name,c.arrive_name,c.need_price";
                $res_inner = $invoice->getInvoiceinner($map_,$field_,false);
                $res_inter = $invoice->getInvoiceinter($map_,$field_,false);
                if($res_inner === false || $res_inter === false){
                    return array('status'=>0,'msg'=>'查询异常');
                    break;
                }
                if(!empty($res_inner)){
                    foreach ($res_inner as $key=>$val){
                        $res_inner[$key]['order_type'] = 'inner';
                    }
                }
                if(!empty($res_inter)){
                    foreach ($res_inter as $k=>$v){
                        $res_inter[$k]['order_type'] = 'inter';
                        ($v['need_price'])&&$res_inter[$k]['need_price'] = $v['need_price']*100;
                    }
                }
                $res['inner'] = $res_inner ? decode_array_2($res_inner):array();
                $res['inter'] = $res_inter ? decode_array_inter_2($res_inter) : array();
                $res_common[$index]['common'] = array_merge($res['inner'],$res['inter']);
            }
        }

        return array('status'=>1,'data'=>$res_common);
    }

    /**
     * 搜索已开发票的订单信息
     * @param $map
     * @param $field
     * @param $page
     * @param $limit
     * @return array|false
     * */
    public function searchInvoice($map,$field='*',$page=1,$limit=10)
    {
        $invoice = new InvoiceModel();
        return $invoice->searchInvoice($map,$field,$page,$limit);
    }

    /**
     * 添加发票
     * @param $data
     * @return string|false
     * */
    public function createInvoiceCommon($data)
    {
        $invoice = new InvoiceModel();
        return $invoice->addInvoiceCommon($data);
    }

    /**
     * 处理发票对应订单的信息
     * @param $data
     * @param $invoice_common_id
     * @return array|false
     * */
    public function createInvoiceOrderRelation($data,$invoice_common_id)
    {
        $invoice = new InvoiceModel();
        $inner_common_ids = $data['inner']['common_id'];
        $inter_common_ids = $data['inter']['id'];
        //城内订单发票
        if(!empty($inner_common_ids)){
            foreach ($inner_common_ids as $i => $id_inner){
                $data_invoice_inner[$i]['order_common_id'] = $id_inner;
                $data_invoice_inner[$i]['invoice_common_id'] = $invoice_common_id;
                $data_invoice_inner[$i]['invoice_type'] = 1;//城内网约车
                $data_invoice_inner[$i]['money'] = $invoice->getInvoiceOrderInner('common_id='.$id_inner,'need_price',false)['need_price'];
            }
        }
        //城际订单发票
        if(!empty($inter_common_ids)){
            foreach ($inter_common_ids as $k => $id_inter){
                $data_invoice_inter[$k]['order_common_id'] = $id_inter;
                $data_invoice_inter[$k]['invoice_common_id'] = $invoice_common_id;
                $data_invoice_inter[$k]['invoice_type'] = 2;//城际拼车
                $data_invoice_inter[$k]['money'] = $invoice->getInvoiceOrderInter('id='.$id_inter,'need_price',false)['need_price']*100;
            }
        }
        empty($data_invoice_inner)&&$data_invoice_inner=array();
        empty($data_invoice_inter)&&$data_invoice_inter=array();
        $data_invoice = array_merge($data_invoice_inner,$data_invoice_inter);
        $res = db('invoice')->insertAll($data_invoice);
        if(empty($res)){
            return array('status'=>0,'msg'=>'系统错误');
        }
        $data_order['handle_bill']=1;
        $inner_common_ids && $invoice->updateOrderInner(array('common_id'=>array('in',$inner_common_ids)),$data_order);
        $inter_common_ids && $invoice->updateOrderInter(array('id'=>array('in',$inter_common_ids)),$data_order);
        return array('status'=>1,'data'=>'');
    }

    /**
     * 添加结算日志
     * @param $data
     * @return string|false
     * */
    public function createPayLog($data)
    {
        $pay_log = new PayLogModel();
        return $pay_log->addPayLog($data);
    }

    /**
     * 更新发票
     * @param $map
     * @param $data
     * @return string|false
     * */
    public function renewInvoiceCommon($map,$data=array())
    {

        $invoice = new InvoiceModel();
        return $invoice->updateInvoiceCommon($map,$data);
    }

    /**
     * 发票支付预处理
     * @param $pay_type
     * @param $uid
     * @param $invoice
     * @return array
     * */
    public function invoicePreDeal($pay_type,$uid,$invoice)
    {
        $extra['invoice_common_id'] = $invoice['invoice_common_id'];
        $extra['name'] = '发票邮寄费';
        $extra['table'] = 'invoice_common';
        switch ($pay_type){
            case 3://余额
                $wallet = new WalletModel();
                $user = new UserModel();
                $wallet_info = $wallet->getWalletByUid($uid);
                if($wallet_info['wallet_money'] < $invoice['postage']){
                    return array('status'=>0,'msg'=>'您的余额不足，请更换支付方式');
                }
                $data['wallet_money'] = $wallet_info['wallet_money']-$invoice['postage'];
                $res = $wallet->updateWallet(array('uid'=>$uid),$data);
                if(!$res){
                    return array('status'=>0,'msg'=>'余额支付出错，请稍后再试');
                }
                $invoice_model = new InvoiceModel();
                $invoice['invoice_status']=2;
                $invoice['pay_type']=3;
                $invoice['pay_time']=time();
                $invoice['pay_account']= Security::decrypt($user->getUserByUid($uid,'user_phone')['user_phone']);
                $invoice_model->updateInvoiceCommon(array(),$invoice);
                return array('status'=>1,'msg'=>'支付成功，请等待邮件');
                break;
            case 2://微信
                $wechat_config = config('wechatPay');
                $wechat_config['notify_url'] = "https://m.xiaomachuxing.cn/api/Callback/wechatInvoiceBack";
                $wechat_config['attach'] = json_encode($extra);
                $data_prepay = Tools::wxPayApi($wechat_config,$invoice['invoice_sn'],abs($invoice['postage']));
                if(array_key_exists('status',$data_prepay)&&$data_prepay['status']==0){
                    return array("status" => 0, "msg" => $data_prepay['msg']);
                }
                return array('status'=>1,'data'=>$data_prepay);
                break;
            case 1://支付宝
                $price = $invoice['postage']/100;//支付宝要求单位为元
                $ali_config = config('aliPay');
                $ali_config['body'] = "小马出行发票邮费支付";
                $ali_config['passback_params'] = $extra;
                $ali_config['setNotifyUrl'] = "https://m.xiaomachuxing.cn/api/Callback/aliInvoiceBack";
                $data_prepay = Tools::alipayApi($ali_config,$invoice['invoice_sn'],abs($price));
                return array('status'=>1,'data'=>$data_prepay);
                break;
            default:
                return array('status'=>0,'msg'=>'支付方式错误');
        }
    }


    /**
     * 取消发票申请
     * @param $invoice_common_id
     * @return array
     * */
    public function cancelInvoiceCommon($invoice_common_id)
    {
        if(empty($invoice_common_id)){
            return array('status'=>0,'msg'=>'参数缺失');
        }
        $invoice_model = new InvoiceModel();
        $map['a.invoice_common_id'] = $invoice_common_id;
        $data['a.is_valid'] = 2;//发票记录公共参数记录失效
        $data['b.invoice_status'] = 4;//发票状态改为已取消
        $data['c.handle_bill'] = 2;//将订单的出具发票状态改为否
        $res_inner = $invoice_model->updateInvoiceInner($map,$data);
        $res_inter = $invoice_model->updateInvoiceInter($map,$data);
        if($res_inner === false || $res_inter === false){
            return array('status'=>0,'msg'=>'更新出错');
        }
        return array('status'=>1,'data'=>'');
    }
}